package arithmetic;

import java.util.*;

public class BinaryTreeTest {

    public static void main(String[] args) {
        // 使用Integer.MIN_VALUE替代null，因为Java数组不能直接存放null值
        Integer[] preorder = {1,2,3,4,5};

        // 转换为int数组，因为Integer.MIN_VALUE不能放在int[]里面
        int[] intPreorder = Arrays.stream(preorder).mapToInt(o -> o instanceof Integer ? (Integer) o : Integer.MIN_VALUE).toArray();

        BinaryTreeTest builder = new BinaryTreeTest();
        TreeNode root = builder.buildTree(intPreorder);
        int i = diameterOfBinaryTree(root);
        System.out.println(i);

    }


    /**
     * 这里是方法
     *
     * @param root
     * @return
     */
    public static int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = recursion(root.left);
        int right = recursion(root.right);
        return left + right + 2;
    }

    public  static int recursion(TreeNode root) {
        //左树的最大深度+右树的最大深度=最长的直径
        //边界条件:节点为空返回
        if (root == null) {
            return 0;
        }
        int left = diameterOfBinaryTree(root.left);
        int right = diameterOfBinaryTree(root.right);
        return Math.max(left, right) + 1;
    }


    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    // 使用索引构建二叉树
    public TreeNode buildTree(int[] nums) {
        return helper(nums, 0);
    }

    // 递归辅助方法
    private TreeNode helper(int[] nums, int index) {
        if (index >= nums.length || nums[index] == Integer.MIN_VALUE) {
            return null; // 使用Integer.MIN_VALUE来代替null
        }

        TreeNode node = new TreeNode(nums[index]);
        node.left = helper(nums, 2 * index + 1);
        node.right = helper(nums, 2 * index + 2);
        return node;
    }


}